# -*- coding: cp936 -*-
import arcpy
import pythonaddins

class NumberToolPathManager(object):
    First_layer = None
    First_layer_full_path = ""
    Field_names = None

    def __init__(self):
        pass

class ComboBoxUpdateValue(object):
    """Implementation for NumberGenerator_addin.combobox_1 (ComboBox)"""
    Gt_value = 1
    def __init__(self):
        self.items = ["1"]
        self.editable = True
        self.enabled = True
        self.dropdownWidth = 'WWW'
        self.width = 'WWW'

    def onSelChange(self, selection):
        ComboBoxUpdateValue.Gt_value = int(selection)
    def onEditChange(self, text):
        ComboBoxUpdateValue.Gt_value = int(text)
    def onFocus(self, focused):
        pass
    def onEnter(self):
        pass
    def refresh(self):
        pass

class ButtonModiffyNumber(object):
    """Implementation for NumberGenerator_addin.button (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False

    def onClick(self):
        ComboBoxUpdateFieldName.Update_variables()
        update_field = ComboBoxUpdateFieldName.Selected_Fieldname
        update_value_start = ComboBoxUpdateValue.Gt_value
        where_sql = "{0} IS NOT NULL".format(update_field)
        cursor = arcpy.UpdateCursor(NumberToolPathManager.First_layer_full_path,where_sql)
        for row in cursor:
            tmp_value = int(row.getValue(update_field))
            if tmp_value > update_value_start:
                row.setValue(update_field, tmp_value + 1)
                cursor.updateRow(row)

class ComboBoxUpdateFieldName(object):
    """Implementation for NumberGenerator_addin.combobox_2 (ComboBox)"""
    Selected_Fieldname = ""

    @staticmethod
    def Update_variables():
        mxd = arcpy.mapping.MapDocument("CURRENT")
        lyr = arcpy.mapping.ListLayers(mxd)[0]
        lyr_full_path = lyr.dataSource
        NumberToolPathManager.First_layer = lyr
        NumberToolPathManager.First_layer_full_path = lyr_full_path
        fields = arcpy.ListFields(lyr_full_path)
        NumberToolPathManager.Field_names = [f.name for f in fields]

    def __init__(self):
        ComboBoxUpdateFieldName.Update_variables()
        self.items = NumberToolPathManager.Field_names
        self.editable = True
        self.enabled = True
        self.dropdownWidth = 'WWWWWW'
        self.width = 'WWWWWW'

    def onSelChange(self, selection):
        ComboBoxUpdateFieldName.Selected_Fieldname = selection
    def onEditChange(self, text):
        pass
    def onFocus(self, focused):
        pass
    def onEnter(self):
        pass
    def refresh(self):
        pass

class NumberGen(object):
    """Implementation for NumberGenerator_addin.tool (Tool)"""
    def __init__(self):
        self.enabled = True
        self.cursor = 3
        self.shape = "Rectangle"  # Can set to "Line", "Circle" or "Rectangle" for interactive shape drawing and to activate the onLine/Polygon/Circle event sinks.
    def onMouseDown(self, x, y, button, shift):
        pass
    def onMouseDownMap(self, x, y, button, shift):
        pass
    def onMouseUp(self, x, y, button, shift):
        pass
    def onMouseUpMap(self, x, y, button, shift):
        pass
    def onMouseMove(self, x, y, button, shift):
        pass
    def onMouseMoveMap(self, x, y, button, shift):
        pass
    def onDblClick(self):
        pass
    def onKeyDown(self, keycode, shift):
        pass
    def onKeyUp(self, keycode, shift):
        pass
    def deactivate(self):
        pass
    def onCircle(self, circle_geometry):
        pass
    def onLine(self, line_geometry):
        pass
    def onRectangle(self, rectangle_geometry):
        extent_backup = arcpy.env.extent
        
        # step 1
        number_field = ComboBoxUpdateFieldName.Selected_Fieldname
        mxd = arcpy.mapping.MapDocument("CURRENT")
        lyr = arcpy.mapping.ListLayers(mxd)[0]
        lyr_full_path = lyr.dataSource
        arr = arcpy.da.TableToNumPyArray(lyr_full_path, number_field, skip_nulls=True)
        arr_number_field = arr[number_field]
        if len(arr_number_field) != 0:
            newID = arr[number_field].max() + 1
        else:
            newID = 1

        # step 2
        Extent = rectangle_geometry
        ExtentPoly = arcpy.Polygon(arcpy.Array([
            arcpy.Point(Extent.XMin, Extent.YMin),
            arcpy.Point(Extent.XMin, Extent.YMax),
            arcpy.Point(Extent.XMax, Extent.YMax),
            arcpy.Point(Extent.XMax, Extent.YMin)
        ]))
        arcpy.SelectLayerByLocation_management(lyr, "WITHIN", ExtentPoly, "#", "NEW_SELECTION")

        # step 3
        arcpy.env.extent = Extent
        arcpy.CalculateField_management(lyr_full_path, number_field, newID, "PYTHON_9.3")
        
        # step 4
        arcpy.env.extent = extent_backup
        arcpy.RefreshActiveView()